package org.shj.thread.book1.findissue;

/**
 * 找找看下面代码有多少处错误
 * @author Administrator
 *
 */
public class BadEnergySource {

	private final long MAXLEVEL = 100;
	private long level = MAXLEVEL;
	private boolean keepRunning = true;
	
	public BadEnergySource(){
		new Thread(new Runnable(){
			public void run(){
				replenish();
			}
		}).start();
	}
	
	public long getUnitsAvailable(){
		return level;
	}
	
	public boolean useEnergy(long units){
		if(units > 0 && level >= units){
			level -= units;
			return true;
		}
		return false;
	}
	
	public void stopEnergySource(){
		keepRunning = false;
	}
	
	private void replenish(){
		while(keepRunning){
			if(level < MAXLEVEL) 
				level++;
			try{
				Thread.sleep(1000);
			}catch(InterruptedException ex){
				
			}
		}		
	}
}


/**
 * 1. 构造方法破坏了类不变式。构造方法中启动了一个线程，这个线程有可能访问尚未初始化的成员变量。
 * 2. 线程资源是有限的，上面每次新建一个对象均会启动一个线程，不可取。
 * 
 */